package cvut.cz.via.android;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import cvut.cz.via.android.courses.Course;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SubscribeCoursesActivity extends ListActivity {
	
	private ArrayList<String> ITEMS; 
	private ArrayList<Course> COURSES;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.subscribe_courses_activity);
		//setListAdapter(new ArrayAdapter<String>(this, R.layout.subscribe_menu_item, ITEMS));
		getCourses();
	}
	
	private void getCourses() {
		
		BufferedReader reader = null;
		String url = "http://vychodniarivia.appspot.com/subject/student";
		try {
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpResponse response = httpclient.execute(new HttpGet(new URI(url)));
		    reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		    StringBuilder sb = new StringBuilder();
		    String str;
		    while((str = reader.readLine()) != null) {
		    	sb.append(str);
		    }
		    
		    Gson gson = new Gson();
		    Type listType = new TypeToken<ArrayList<Course>>() {}.getType();
		    COURSES = gson.fromJson(sb.toString(), listType);
		    //Log.d("COURSES", COURSES.toString());
		} catch (Exception e) {
			Log.d("EXCEPTION", e.getLocalizedMessage());
		}
		
		setItems();
		
	}

	private void setItems() {
		ITEMS = new ArrayList<String>();
		for (int i = 0; i < COURSES.size(); i++) {
			ITEMS.add(COURSES.get(i).getCode());
		}
		setListAdapter(new ArrayAdapter<String>(this, R.layout.courses_menu_item, ITEMS));
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		StudyMaterialsApplication sma = getStudyMaterialsApplication();
		sma.actualCourse = COURSES.get(position);
		Intent intent = new Intent(SubscribeCoursesActivity.this, CourseInfoActivity.class);		
		startActivity(intent);		
	}
	
	private StudyMaterialsApplication getStudyMaterialsApplication() {
		StudyMaterialsApplication sma = (StudyMaterialsApplication)getApplication();
		return sma;
	}	
}
